﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Threading;



/// <summary>
/// Summary description for LogHelper
/// </summary>
public class LogHelper
{
	public LogHelper()
	{
		//
		// TODO: Add constructor logic here
		//      
	}

    static LogHelper()
    {
        Thread t = new Thread(new ThreadStart(WriteLog_WaitCallback));
        t.IsBackground = false;
        t.Start();
    }


    private static List<KeyValuePair<String, Boolean>> _dic = new List<KeyValuePair<String, Boolean>>();

    private static object state = new object();

    /// <summary>
    /// 现在只是实现了最简单形式的log，以后可以进行重载实现更多格式的log
    /// </summary>
    /// <param name="content"></param>
    public static void WriteLog(String content,Boolean isException)
    {
        if (!String.IsNullOrEmpty(content))
        {

            KeyValuePair<String, Boolean> kv = new KeyValuePair<String, Boolean>(content, isException);
            _dic.Add(kv);         

        }
    }

    public static void WriteLog(String content)
    {
        WriteLog(content, false);
    }

    private static void WriteLog_WaitCallback()
    {
        while (true)
        {

            KeyValuePair<String, Boolean>[] m_dic;

            lock (state)
            {
                m_dic = _dic.ToArray();
                _dic.Clear();
            }

            if (m_dic.Length == 0)
            {
                //  sleep for this time
                Thread.Sleep(3000);
            }
            else
            {

                foreach (KeyValuePair<String, Boolean> item in m_dic)
                {
                    String path = "~\\log";
                    DateTime dt = DateTime.Today;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    String filePath = Path.Combine(path, dt.ToString("yyyyMMdd") + ((Boolean)item.Value ? ".exp" : "") + ".log");
                    using (StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
                    {
                        sw.WriteLine(String.Format("{0}:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), (String)item.Key));
                    }
                }
            }    
        }
    }  
    
}

